package com.lovcreate.listener;


import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by Administrator on 2016/7/26.
 */
public class JdbcListener implements ServletContextListener{

    // 数据库连接
    Connection conn = null;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext sc = servletContextEvent.getServletContext();    // 由事件得到 ServletContext
        // 使用上下文得到初始化参数
        String driver = sc.getInitParameter("driver");
        String url = sc.getInitParameter("url");
        String user = sc.getInitParameter("user");
        String pwd = sc.getInitParameter("pwd");

        try {
            Class.forName(driver);      // 加载数据库驱动
            // 获得数据库连接
            conn = DriverManager.getConnection(url,user,pwd);
            sc.setAttribute("conn",conn);       // 把数据库连接存储为上下文的一个属性，使得Web应用的各个部分都能访问
        } catch (ClassNotFoundException e) {
            // 处理Class.forName 错误
            e.printStackTrace();
        } catch (SQLException e) {
            // 处理JDBC错误
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        try {
            conn.close();   // 上下文撤销的时候关闭数据库连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
